package qc.module.platform.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.module.platform.dto.apiFilter.ApiFilterDto;
import qc.module.platform.entity.QcApiFilters;

import java.util.Date;
import java.util.List;

/**
 * ApiFilterMapper
 *
 * @author QuCheng Tech
 * @create 2023/11/03
 */
@Mapper
public interface ApiFilterMapper {

    ApiFilterMapper MAPPER = Mappers.getMapper(ApiFilterMapper.class);

    /**
     * dto -> entity
     */
    @Mapping(target = "flag", ignore = true)
    @Mapping(target = "updateTm", ignore = true)
    @Mapping(target = "hittm", ignore = true)
    QcApiFilters toEntity(ApiFilterDto dto);


    /**
     * entity -> dto
     */
    @Mapping(target = "flag", source = "flag.index")
    @Mapping(target = "updateTm", source = "updateTm", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(target = "hittm", source = "hittm", dateFormat = "yyyy-MM-dd HH:mm:ss")
    ApiFilterDto toDto(QcApiFilters en);

    /**
     * enList -> dtoList
     */
    List<ApiFilterDto> toDtoList(List<QcApiFilters> enList);

    /**
     * 新增或修改dto -> entity
     */
    default QcApiFilters addOrUpdateDtoToEntity(ApiFilterDto dto) {
        // 1.dto转为entity
        QcApiFilters en = ApiFilterMapper.MAPPER.toEntity(dto);

        // 2.设置命中次数、规则更新时间默认值
        en.setHitcount(0x0);
        en.setUpdateTm(new Date());

        // 3.处理标记，非空时进行转换，空值时使用默认
        Integer flag = null;
        if (dto.getFlag() != null) {
            try {
                flag = dto.getFlag();
            } catch (NumberFormatException exception) {
                //转换错误不处理，使用默认状态
            }
        }
        en.setFlag(getResourceStatusFlagEnum(flag));

        return en;
    }

    static ResourceStatusFlagEnum getResourceStatusFlagEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (ResourceStatusFlagEnum item : ResourceStatusFlagEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return ResourceStatusFlagEnum.NORMAL;
    }
}
